#include "sweety_Input.h"
#include "framework/sweety.h"
#include "third-party/glfw/include/glfw3.h"

namespace SW
{
	Input* Input::s_Instance = nullptr;

	bool Input::m_IsScroll = false;
	float Input::m_Yoffset = 0.f;

	Input* Input::GetInstance()
	{
		if (!s_Instance)
		{
			return s_Instance = new Input;
		}			
		return s_Instance;
	}

	Input::Input()
	{
		m_Window = nullptr;
	}

	void Input::Scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
	{
		m_IsScroll = true;
		m_Yoffset = yoffset;				
	}

	bool Input::IsKeyPressed(int keycode)
	{
		auto window = INPUT_GLFW_WINDOW_PTR;
		SW_ASSERT(window != NULL);
		int status = glfwGetKey(window, keycode);
		return status == GLFW_PRESS || status == GLFW_REPEAT;
	}

	bool Input::IsMouseButtonPressed(int mousecode)
	{
		auto window = INPUT_GLFW_WINDOW_PTR;
		SW_ASSERT(window != NULL);
		int status = glfwGetMouseButton(window, mousecode);
		return status == GLFW_PRESS;
	}

	std::pair<float, float> Input::GetMousePosition()
	{
		double xpos, ypos;
		auto window = INPUT_GLFW_WINDOW_PTR;
		SW_ASSERT(window != NULL);
		glfwGetCursorPos(window, &xpos, &ypos);

		return std::pair<float, float>((float)xpos, (float)ypos);
	}

	float Input::GetMouseX()
	{
		return GetMousePosition().first;
	}

	float Input::GetMouseY()
	{
		return GetMousePosition().second;
	}

	float Input::GetYoffset()
	{
		if (m_IsScroll)
		{
			m_IsScroll = false;
			return m_Yoffset;
		}
		return 0.f;
	}

	void Input::SetWindow(GLFWwindow* window)
	{
		GetInstance()->m_Window = window;
		glfwSetScrollCallback(window, Scroll_callback);
	}

	void Input::FreeInstance()
	{
		if (s_Instance)
		{
			delete s_Instance;
			s_Instance = nullptr;
		}
	}
}
